/**
 * 仪表盘组件
 * Dashboard Component
 */

class Dashboard {
  constructor() {
    this.currentView = 'dashboard';
    this.sidebarOpen = false;
    this.init();
  }

  /**
   * 初始化仪表盘
   */
  init() {
    this.bindEvents();
    this.initSidebar();
    this.initSearch();
    this.initStorage();
    this.updateUserInfo();
    this.loadDashboardData();
    this.updateDateTime();
    
    // 每分钟更新时间
    setInterval(() => this.updateDateTime(), 60000);
  }

  /**
   * 绑定事件
   */
  bindEvents() {
    // 移动端菜单切换
    const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
    if (mobileMenuToggle) {
      mobileMenuToggle.addEventListener('click', () => this.toggleSidebar());
    }

    // 侧边栏关闭按钮
    const sidebarClose = document.getElementById('sidebar-close');
    if (sidebarClose) {
      sidebarClose.addEventListener('click', () => this.closeSidebar());
    }

    // 遮罩层点击关闭
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    if (sidebarOverlay) {
      sidebarOverlay.addEventListener('click', () => this.closeSidebar());
    }

    // 导航菜单项点击
    const navItems = document.querySelectorAll('[data-page]');
    navItems.forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        const page = item.dataset.page;
        this.switchView(page);
      });
    });

    // 用户菜单
    const userMenuBtn = document.getElementById('user-menu-btn');
    const userMenu = document.getElementById('user-menu');
    if (userMenuBtn && userMenu) {
      userMenuBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        userMenu.classList.toggle('hidden');
      });

      // 点击其他地方关闭用户菜单
      document.addEventListener('click', () => {
        userMenu.classList.add('hidden');
      });
    }

    // 退出登录
    const logoutBtn = document.getElementById('logout-btn');
    if (logoutBtn) {
      logoutBtn.addEventListener('click', () => this.handleLogout());
    }



    // 快速操作按钮
    const newNoteBtn = document.getElementById('new-note-btn');
    if (newNoteBtn) {
      newNoteBtn.addEventListener('click', () => this.handleNewNote());
    }

    const uploadFileBtn = document.getElementById('upload-file-btn');
    if (uploadFileBtn) {
      uploadFileBtn.addEventListener('click', () => this.handleUploadFile());
    }

    // 响应式处理
    window.addEventListener('resize', () => this.handleResize());
  }

  /**
   * 初始化侧边栏
   */
  initSidebar() {
    this.handleResize();
  }

  /**
   * 初始化搜索功能
   */
  initSearch() {
    this.searchComponent = new SearchComponent();
  }

  /**
   * 初始化存储组件
   */
  initStorage() {
    this.storageComponent = new StorageComponent();
    // 将存储组件设为全局可访问，供模态框使用
    window.storageComponent = this.storageComponent;
  }

  /**
   * 切换侧边栏
   */
  toggleSidebar() {
    if (this.sidebarOpen) {
      this.closeSidebar();
    } else {
      this.openSidebar();
    }
  }

  /**
   * 打开侧边栏
   */
  openSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    
    if (sidebar) {
      sidebar.classList.remove('-translate-x-full');
      this.sidebarOpen = true;
    }
    
    if (overlay) {
      overlay.classList.remove('hidden');
    }
  }

  /**
   * 关闭侧边栏
   */
  closeSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    
    if (sidebar) {
      sidebar.classList.add('-translate-x-full');
      this.sidebarOpen = false;
    }
    
    if (overlay) {
      overlay.classList.add('hidden');
    }
  }

  /**
   * 切换视图
   */
  switchView(viewName) {
    // 更新导航状态
    const navItems = document.querySelectorAll('[data-page]');
    navItems.forEach(item => {
      if (item.dataset.page === viewName) {
        item.classList.add('nav-item-active');
      } else {
        item.classList.remove('nav-item-active');
      }
    });

    // 切换内容显示
    const contents = ['dashboard-content', 'notes-content', 'files-content'];
    contents.forEach(contentId => {
      const content = document.getElementById(contentId);
      if (content) {
        if (contentId === `${viewName}-content`) {
          content.classList.remove('hidden');
        } else {
          content.classList.add('hidden');
        }
      }
    });

    this.currentView = viewName;

    // 在移动端切换视图后关闭侧边栏
    if (window.innerWidth < 1024) {
      this.closeSidebar();
    }

    // 根据视图加载相应数据
    this.loadViewData(viewName);
  }

  /**
   * 加载视图数据
   */
  async loadViewData(viewName) {
    try {
      switch (viewName) {
        case 'dashboard':
          await this.loadDashboardData();
          break;
        case 'notes':
          // 初始化笔记管理器
          if (!this.notesManager) {
            this.notesManager = new NotesManager();
          } else {
            await this.notesManager.refresh();
          }
          break;
        case 'files':
          // 初始化文件管理器
          if (typeof FileManager !== 'undefined') {
            if (!this.fileManager) {
              this.fileManager = new FileManager();
            } else {
              await this.fileManager.refresh();
            }
          } else {
            console.warn('FileManager未定义，文件管理功能不可用');
            notification.warning('文件管理功能暂时不可用');
          }
          break;
      }
    } catch (error) {
      console.error(`加载${viewName}数据失败:`, error);
      notification.error(`加载数据失败 / Failed to load data`);
    }
  }

  /**
   * 加载仪表盘数据
   */
  async loadDashboardData() {
    try {
      // 并行加载各种统计数据
      const [notesStats, filesStats, storageStats] = await Promise.all([
        this.loadNotesStats(),
        this.loadFilesStats(),
        this.loadStorageStats()
      ]);

      // 更新统计卡片
      this.updateStatsCards(notesStats, filesStats, storageStats);

      // 加载最近内容
      await Promise.all([
        this.loadRecentNotes(),
        this.loadRecentFiles()
      ]);

    } catch (error) {
      console.error('加载仪表盘数据失败:', error);
      notification.error('加载仪表盘数据失败 / Failed to load dashboard data');
    }
  }

  /**
   * 加载笔记统计
   */
  async loadNotesStats() {
    try {
      const response = await api.get('/notes/stats/summary');
      return response.stats || { total: 0, thisWeek: 0 };
    } catch (error) {
      console.error('加载笔记统计失败:', error);
      return { total: 0, thisWeek: 0 };
    }
  }

  /**
   * 加载文件统计
   */
  async loadFilesStats() {
    try {
      const response = await api.get('/files/storage/stats');
      return response.stats || { total: 0, thisWeek: 0 };
    } catch (error) {
      console.error('加载文件统计失败:', error);
      return { total: 0, thisWeek: 0 };
    }
  }

  /**
   * 加载存储统计
   */
  async loadStorageStats() {
    try {
      const response = await api.get('/files/storage/stats');
      return response.stats;
    } catch (error) {
      console.error('加载存储统计失败:', error);
      return {
        used: 0,
        limit: 32212254720, // 30GB
        usagePercentage: 0
      };
    }
  }

  /**
   * 更新统计卡片
   */
  updateStatsCards(notesStats, filesStats, storageStats) {
    // 更新笔记统计
    const notesCount = document.getElementById('notes-count');
    if (notesCount) {
      notesCount.textContent = notesStats.total;
    }

    // 更新文件统计
    const filesCount = document.getElementById('files-count');
    if (filesCount) {
      filesCount.textContent = filesStats.total;
    }

    // 更新存储统计
    this.updateStorageDisplay(storageStats);
  }

  /**
   * 更新存储显示
   */
  updateStorageDisplay(storageStats) {
    const formatBytes = (bytes) => {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    // 更新顶部存储显示
    const storageUsage = document.getElementById('storage-usage');
    if (storageUsage) {
      storageUsage.textContent = `${formatBytes(storageStats.used)} / ${formatBytes(storageStats.limit)}`;
    }

    // 更新卡片存储显示
    const storageUsageCard = document.getElementById('storage-usage-card');
    if (storageUsageCard) {
      storageUsageCard.textContent = formatBytes(storageStats.used);
    }

    const storagePercentage = document.getElementById('storage-percentage');
    if (storagePercentage) {
      storagePercentage.textContent = `${storageStats.usagePercentage}%`;
    }

    // 更新侧边栏存储进度
    const storageProgress = document.getElementById('storage-progress');
    if (storageProgress) {
      storageProgress.style.width = `${storageStats.usagePercentage}%`;
      
      // 根据使用率改变颜色
      if (storageStats.usagePercentage > 90) {
        storageProgress.className = 'bg-red-500 h-2 rounded-full transition-all duration-300';
      } else if (storageStats.usagePercentage > 70) {
        storageProgress.className = 'bg-warning h-2 rounded-full transition-all duration-300';
      } else {
        storageProgress.className = 'bg-primary h-2 rounded-full transition-all duration-300';
      }
    }

    const storageUsed = document.getElementById('storage-used');
    const storageTotal = document.getElementById('storage-total');
    if (storageUsed) storageUsed.textContent = formatBytes(storageStats.used);
    if (storageTotal) storageTotal.textContent = formatBytes(storageStats.limit);
  }

  /**
   * 加载最近笔记
   */
  async loadRecentNotes() {
    try {
      const response = await api.get('/notes/recent/list?limit=5');
      const notes = response.data || [];
      this.renderRecentNotes(notes);
    } catch (error) {
      console.error('加载最近笔记失败:', error);
      this.renderRecentNotes([]);
    }
  }

  /**
   * 加载最近文件
   */
  async loadRecentFiles() {
    try {
      const response = await api.get('/files?page=1&pageSize=5&sortBy=created_at&sortOrder=desc');
      const files = response.data || [];
      this.renderRecentFiles(files);
    } catch (error) {
      console.error('加载最近文件失败:', error);
      this.renderRecentFiles([]);
    }
  }

  /**
   * 渲染最近笔记
   */
  renderRecentNotes(notes) {
    const container = document.getElementById('recent-notes');
    if (!container) return;

    if (notes.length === 0) {
      container.innerHTML = `
        <div class="text-center py-8 text-neutral-500">
          <i class="fa fa-sticky-note text-2xl mb-2"></i>
          <p>暂无笔记</p>
        </div>
      `;
      return;
    }

    const formatTime = (dateString) => {
      const date = new Date(dateString);
      const now = new Date();
      const diff = now - date;
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      
      if (days === 0) return '今天';
      if (days === 1) return '昨天';
      if (days < 7) return `${days}天前`;
      return date.toLocaleDateString();
    };

    container.innerHTML = notes.map(note => `
      <div class="flex items-center gap-3 p-3 rounded-md hover:bg-neutral-50 cursor-pointer transition-colors">
        <div class="w-8 h-8 bg-blue-100 rounded-md flex items-center justify-center flex-shrink-0">
          <i class="fa fa-sticky-note text-blue-600"></i>
        </div>
        <div class="flex-1 min-w-0">
          <p class="font-medium text-neutral-800 truncate">${note.title}</p>
          <p class="text-sm text-neutral-500">${formatTime(note.updated_at)}</p>
        </div>
        <i class="fa fa-chevron-right text-neutral-300"></i>
      </div>
    `).join('');
  }

  /**
   * 渲染最近文件
   */
  renderRecentFiles(files) {
    const container = document.getElementById('recent-files');
    if (!container) return;

    if (files.length === 0) {
      container.innerHTML = `
        <div class="text-center py-8 text-neutral-500">
          <i class="fa fa-folder text-2xl mb-2"></i>
          <p>暂无文件</p>
        </div>
      `;
      return;
    }

    const getFileIcon = (fileType) => {
      const icons = {
        image: 'fa-image text-green-600',
        video: 'fa-video-camera text-red-600',
        audio: 'fa-music text-purple-600',
        document: 'fa-file-text text-blue-600',
        other: 'fa-file text-neutral-600'
      };
      return icons[fileType] || icons.other;
    };

    const formatTime = (dateString) => {
      const date = new Date(dateString);
      const now = new Date();
      const diff = now - date;
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      
      if (days === 0) return '今天';
      if (days === 1) return '昨天';
      if (days < 7) return `${days}天前`;
      return date.toLocaleDateString();
    };

    container.innerHTML = files.map(file => `
      <div class="flex items-center gap-3 p-3 rounded-md hover:bg-neutral-50 cursor-pointer transition-colors">
        <div class="w-8 h-8 bg-neutral-100 rounded-md flex items-center justify-center flex-shrink-0">
          <i class="fa ${getFileIcon(file.file_type)}"></i>
        </div>
        <div class="flex-1 min-w-0">
          <p class="font-medium text-neutral-800 truncate">${file.original_name}</p>
          <p class="text-sm text-neutral-500">${formatTime(file.created_at)}</p>
        </div>
        <i class="fa fa-chevron-right text-neutral-300"></i>
      </div>
    `).join('');
  }

  /**
   * 更新用户信息
   */
  updateUserInfo() {
    const user = auth.getCurrentUser();
    if (user) {
      const userName = document.getElementById('user-name');
      if (userName) {
        userName.textContent = user.nickname || user.email || '用户';
      }
    }
  }

  /**
   * 更新日期时间
   */
  updateDateTime() {
    const currentDate = document.getElementById('current-date');
    if (currentDate) {
      const now = new Date();
      const options = { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric',
        weekday: 'long'
      };
      currentDate.textContent = now.toLocaleDateString('zh-CN', options);
    }
  }

  /**
   * 处理响应式变化
   */
  handleResize() {
    if (window.innerWidth >= 1024) {
      // 桌面端：确保侧边栏显示
      this.closeSidebar();
    }
  }



  /**
   * 处理新建笔记
   */
  handleNewNote() {
    window.location.href = '/note-editor.html';
  }

  /**
   * 处理文件上传
   */
  handleUploadFile() {
    // 切换到文件管理页面
    this.switchView('files');
    
    // 延迟一下确保文件管理器已初始化
    setTimeout(() => {
      if (this.fileManager && typeof this.fileManager.toggleUploadArea === 'function') {
        this.fileManager.toggleUploadArea();
      } else if (typeof FileManager !== 'undefined') {
        // 如果文件管理器未初始化，尝试初始化
        this.fileManager = new FileManager();
        if (typeof this.fileManager.toggleUploadArea === 'function') {
          this.fileManager.toggleUploadArea();
        }
      } else {
        // 直接显示上传区域
        const uploadArea = document.getElementById('upload-area');
        if (uploadArea) {
          uploadArea.classList.toggle('hidden');
        }
      }
    }, 100);
  }

  /**
   * 处理退出登录
   */
  async handleLogout() {
    try {
      await auth.logout();
      notification.success('已退出登录 / Logged out successfully');
      window.location.reload();
    } catch (error) {
      console.error('退出登录失败:', error);
      notification.error('退出登录失败 / Logout failed');
    }
  }

  /**
   * 刷新仪表盘数据
   */
  async refresh() {
    await this.loadDashboardData();
    notification.success('数据已刷新 / Data refreshed');
  }

  /**
   * 获取当前视图
   */
  getCurrentView() {
    return this.currentView;
  }
}

// 导出Dashboard类
window.Dashboard = Dashboard;